<template>
  <el-dialog
    v-model="visible"
    title="添加人员"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="add-members-dialog">
      <!-- 群聊名称设置 -->
      <div class="group-name-section">
        <el-form-item label="群聊名称">
          <el-input
            v-model="groupName"
            placeholder="请输入群聊名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </div>

      <!-- 用户搜索 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户"
          clearable
          @input="searchUsers"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 用户列表 -->
      <div class="user-list">
        <div class="list-header">
          <span>选择用户</span>
          <span class="selected-count">已选择 {{ selectedCount }} 人</span>
        </div>
        
        <div class="user-list-content">
          <div
            v-for="user in filteredUsers"
            :key="user.userId"
            class="user-item"
            :class="{ 'selected': isUserSelected(user.userId) }"
            @click="toggleUser(user)"
          >
            <el-checkbox
              :model-value="isUserSelected(user.userId)"
              @change="toggleUser(user)"
            />
            <el-avatar :src="user.avatar" :size="40" class="user-avatar">
              {{ user.nickName?.charAt(0) || user.userName?.charAt(0) }}
            </el-avatar>
            <div class="user-info">
              <div class="user-name">{{ user.nickName || user.userName }}</div>
              <div class="user-detail">{{ user.email || user.phonenumber || '暂无联系方式' }}</div>
            </div>
            <div class="user-status" :class="user.imStatus === 'online' ? 'online' : 'offline'">
              {{ user.imStatus === 'online' ? '在线' : '离线' }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="testBackend" type="info" size="small">测试后端</el-button>
        <el-button
          type="primary"
          :disabled="selectedCount === 0"
          :loading="creating"
          @click.stop="handleCreateGroup"
        >
          创建群聊 ({{ selectedCount }}人)
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getImUserList, createGroup } from '@/api/im'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success', 'close'])

const visible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 表单数据
const groupName = ref('')
const searchKeyword = ref('')
const selectedUsers = ref([])
const allUsers = ref([])
const creating = ref(false)

// 过滤后的用户列表
const filteredUsers = computed(() => {
  if (!searchKeyword.value) return allUsers.value
  
  return allUsers.value.filter(user => {
    const username = user.userName?.toLowerCase() || ''
    const nickname = user.nickName?.toLowerCase() || ''
    const keyword = searchKeyword.value.toLowerCase()
    
    return username.includes(keyword) || nickname.includes(keyword)
  })
})

// 选中用户数量
const selectedCount = computed(() => selectedUsers.value.length)

// 搜索用户
const searchUsers = () => {
  // 实时搜索，通过computed属性实现
}

// 加载用户列表
const loadUsers = async () => {
  try {
    console.log('开始加载用户列表...')
    
    // 检查认证状态
    const token = localStorage.getItem('Admin-Token')
    console.log('loadUsers - 当前Token:', token ? '存在' : '不存在')
    console.log('loadUsers - Token值:', token)
    
    const response = await getImUserList()
    console.log('用户列表响应:', response)
    
    if (response.code === 200) {
      // 过滤掉当前用户
      allUsers.value = (response.data || []).filter(user => 
        user.userId !== userStore.userId
      )
      console.log('过滤后的用户列表:', allUsers.value)
    } else {
      console.error('加载用户列表失败，响应:', response)
      ElMessage.error('加载用户列表失败: ' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('加载用户列表失败，详细错误:', error)
    console.error('错误堆栈:', error.stack)
    ElMessage.error('加载用户列表失败: ' + (error.message || '未知错误'))
  }
}

// 检查用户是否已选择
const isUserSelected = (userId) => {
  return selectedUsers.value.some(user => user.userId === userId)
}

// 切换用户选择状态
const toggleUser = (user) => {
  console.log('toggleUser被调用，用户:', user)
  const index = selectedUsers.value.findIndex(u => u.userId === user.userId)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
    console.log('移除用户，当前选中:', selectedUsers.value.length)
  } else {
    selectedUsers.value.push(user)
    console.log('添加用户，当前选中:', selectedUsers.value.length)
  }
}

// 创建群聊
const handleCreateGroup = async () => {
  console.log('createGroup被调用，当前状态:', { 
    selectedCount: selectedUsers.value.length, 
    creating: creating.value 
  })
  
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一个用户')
    return
  }

  // 防止重复调用
  if (creating.value) {
    console.log('正在创建群聊中，请勿重复点击')
    return
  }

  creating.value = true
  
  try {
    const groupData = {
      groupName: groupName.value || `多人聊天(${selectedUsers.value.length + 1}人)`,
      description: '',
      avatar: '',
      memberIds: selectedUsers.value.map(user => {
        const userId = parseInt(user.userId)
        console.log('用户ID转换:', user.userId, '->', userId, '类型:', typeof userId)
        return userId
      })
    }

    console.log('准备创建群聊，数据:', groupData)
    console.log('选中的用户:', selectedUsers.value)

    console.log('开始调用createGroup API...')
    console.log('API URL应该是: /im/group/create')
    console.log('发送的数据:', groupData)
    
    // 检查认证状态
    const token = localStorage.getItem('Admin-Token')
    console.log('当前Token:', token ? '存在' : '不存在')
    console.log('Token值:', token)
    
    let response
    try {
      console.log('开始调用createGroup API...')
      console.log('调用createGroup前的状态检查...')
      
      // 检查防重复提交状态
      const sessionObj = JSON.parse(localStorage.getItem('sessionObj') || '{}')
      console.log('当前sessionObj:', sessionObj)
      
      // 临时清除防重复提交状态
      console.log('临时清除防重复提交状态...')
      localStorage.removeItem('sessionObj')
      
      // 临时重置创建状态
      console.log('临时重置创建状态...')
      creating.value = false
      
      response = await createGroup(groupData)
      console.log('createGroup API调用完成，响应:', response)
      console.log('响应类型:', typeof response)
      console.log('响应是否为null:', response === null)
      console.log('响应是否为undefined:', response === undefined)
    } catch (apiError) {
      console.error('createGroup API调用失败:', apiError)
      console.error('API错误详情:', {
        message: apiError.message,
        response: apiError.response,
        status: apiError.response?.status,
        data: apiError.response?.data,
        stack: apiError.stack
      })
      ElMessage.error('API调用失败: ' + (apiError.message || '未知错误'))
      return
    }
    
    // 检查响应是否存在
    if (!response) {
      console.error('API调用返回undefined，可能是网络错误或后端服务未启动')
      ElMessage.error('网络错误：无法连接到服务器')
      return
    }
    
    // 检查响应格式
    if (typeof response !== 'object') {
      console.error('API响应格式错误:', typeof response, response)
      ElMessage.error('服务器响应格式错误')
      return
    }
    
    if (response.code === 200) {
      ElMessage.success('群聊创建成功')
      emit('success', response.data)
      handleClose()
    } else {
      console.error('创建群聊失败，响应:', response)
      ElMessage.error(response.msg || '创建群聊失败')
    }
  } catch (error) {
    console.error('创建群聊失败，详细错误:', error)
    console.error('错误堆栈:', error.stack)
    ElMessage.error('创建群聊失败: ' + (error.message || '未知错误'))
  } finally {
    creating.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置表单
  groupName.value = ''
  searchKeyword.value = ''
  selectedUsers.value = []
  // 重置创建状态
  creating.value = false
  emit('close')
}

// 测试后端连接
const testBackend = async () => {
  try {
    console.log('测试后端连接...')
    
    // 测试用户列表API
    console.log('1. 测试用户列表API...')
    const userResponse = await getImUserList()
    console.log('用户列表API测试结果:', userResponse)
    
    // 测试表检查API（跳过，可能有权限问题）
    console.log('2. 跳过表检查API测试（可能有权限问题）')
    
    // 测试IM模块是否启动
    console.log('3. 测试IM模块是否启动...')
    try {
      const testResponse = await fetch('/im/test')
      console.log('IM模块测试响应状态:', testResponse.status, testResponse.statusText)
      
      if (testResponse.ok) {
        const testData = await testResponse.json()
        console.log('IM模块测试结果:', testData)
      } else {
        console.error('IM模块测试失败，状态码:', testResponse.status)
        const errorText = await testResponse.text()
        console.error('错误响应内容:', errorText)
      }
    } catch (testError) {
      console.error('IM模块测试异常:', testError)
    }
    
    // 测试创建群聊API路径
    console.log('3.1 测试创建群聊API路径...')
    try {
      const groupTestResponse = await fetch('/im/group/test')
      console.log('创建群聊API测试响应状态:', groupTestResponse.status, groupTestResponse.statusText)
      
      if (groupTestResponse.ok) {
        const groupTestData = await groupTestResponse.json()
        console.log('创建群聊API测试结果:', groupTestData)
      } else {
        console.error('创建群聊API测试失败，状态码:', groupTestResponse.status)
        const errorText = await groupTestResponse.text()
        console.error('错误响应内容:', errorText)
      }
    } catch (groupTestError) {
      console.error('创建群聊API测试异常:', groupTestError)
    }
    
    // 测试创建群聊API（不实际创建）
    console.log('4. 测试创建群聊API路径...')
    try {
      const testGroupData = {
        groupName: '测试群聊',
        description: '',
        avatar: '',
        memberIds: [1]
      }
      console.log('测试数据:', testGroupData)
      
      // 使用fetch直接调用，绕过axios拦截器
      console.log('4.1 使用fetch直接调用API...')
      const fetchResponse = await fetch('/im/group/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
        },
        body: JSON.stringify(testGroupData)
      })
      console.log('fetch原始响应状态:', fetchResponse.status, fetchResponse.statusText)
      console.log('fetch原始响应headers:', fetchResponse.headers)
      
      if (fetchResponse.ok) {
        const fetchData = await fetchResponse.json()
        console.log('fetch解析结果:', fetchData)
      } else {
        console.error('fetch请求失败，状态码:', fetchResponse.status)
        const errorText = await fetchResponse.text()
        console.error('错误响应内容:', errorText)
      }
      
      // 使用axios调用
      console.log('4.2 使用axios调用API...')
      try {
        const testResponse = await createGroup(testGroupData)
        console.log('axios调用成功，结果:', testResponse)
      } catch (axiosError) {
        console.error('axios调用失败:', axiosError)
        console.error('axios错误详情:', {
          message: axiosError.message,
          response: axiosError.response,
          status: axiosError.response?.status,
          data: axiosError.response?.data
        })
      }
      
    } catch (apiError) {
      console.error('创建群聊API测试失败:', apiError)
    }
    
    ElMessage.success('后端连接测试完成，请查看控制台日志')
  } catch (error) {
    console.error('后端连接测试失败:', error)
    ElMessage.error('后端连接失败: ' + (error.message || '未知错误'))
  }
}

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    loadUsers()
    // 设置默认群聊名称
    groupName.value = '多人聊天'
  }
})
</script>

<style scoped>
.add-members-dialog {
  .group-name-section {
    margin-bottom: 20px;
  }

  .search-section {
    margin-bottom: 16px;
  }

  .user-list {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    max-height: 400px;
    overflow: hidden;

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      background: #f8f9fa;
      border-bottom: 1px solid #e4e7ed;
      font-size: 14px;
      font-weight: 500;

      .selected-count {
        color: #409eff;
        font-size: 12px;
      }
    }

    .user-list-content {
      max-height: 300px;
      overflow-y: auto;

      .user-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        cursor: pointer;
        transition: all 0.2s;
        border-bottom: 1px solid #f0f0f0;

        &:hover {
          background: #f5f7fa;
        }

        &.selected {
          background: #e3f2fd;
        }

        &:last-child {
          border-bottom: none;
        }

        .user-avatar {
          margin: 0 12px;
        }

        .user-info {
          flex: 1;
          min-width: 0;

          .user-name {
            font-weight: 500;
            color: #333;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .user-detail {
            font-size: 12px;
            color: #666;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .user-status {
          font-size: 12px;
          color: #999;

          &.online {
            color: #4caf50;
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
